package org.luxor.commons.selenium.config;

import org.luxor.commons.selenium.client.SeleniumClient;
import org.luxor.commons.selenium.client.impl.SeleniumClientImpl;
import org.luxor.commons.selenium.component.SeleniumDriverCreator;
import org.luxor.commons.selenium.config.properties.SeleniumProperties;
import org.luxor.commons.selenium.listener.AbstractSeleniumEventListener;
import org.luxor.commons.selenium.listener.SeleniumEventListener;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.List;


/**
 * Selenium 全局配置
 *
 * @author Mr.Yan  @date: 2022/03/21
 */
@Configuration
@EnableConfigurationProperties(SeleniumProperties.class)
@ConditionalOnProperty(prefix = SeleniumProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class SeleniumAutoConfig {
    private static final Logger log = LoggerFactory.getLogger(SeleniumAutoConfig.class);

    @Bean
    @ConditionalOnMissingBean(WebDriver.class)
    public WebDriver webDriver(SeleniumProperties seleniumProperties) {
        log.info("Initialize checks the instantiation of the  SeleniumDriver...");
        SeleniumDriverCreator seleniumDriver = new SeleniumDriverCreator();
        WebDriver checkWebDriver = seleniumDriver.creatorSeleniumDriver(seleniumProperties);
        checkWebDriver.quit();
        log.info("Initialize checks the instantiation of the  SeleniumDriver, complete");
        return checkWebDriver;
    }

    @Bean
    @Order(-1)
    @ConditionalOnMissingBean(name = "defaultSeleniumEventListener")
    public SeleniumEventListener defaultSeleniumEventListener() {
        return new AbstractSeleniumEventListener();
    }

    @Bean
    @ConditionalOnMissingBean
    public SeleniumClient seleniumClient(SeleniumProperties seleniumProperties,
                                         ObjectProvider<List<SeleniumEventListener>> listeners) {
        log.info("Initialize the instantiation of seleniumCoreService...");
        SeleniumClient seleniumClient = new SeleniumClientImpl(seleniumProperties, listeners.getIfUnique());
        log.info("Initialize the instantiation of seleniumCoreService, complete");
        return seleniumClient;
    }

}
